package com.ruoyi.system.service.impl;

import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.dto.CommunityResidentDto;
import com.ruoyi.system.domain.CommunityFacilities;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.CommunityResidentMapper;
import com.ruoyi.system.domain.CommunityResident;
import com.ruoyi.system.service.ICommunityResidentService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 住户管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-27
 */
@Service
public class CommunityResidentServiceImpl implements ICommunityResidentService 
{
    @Autowired
    private CommunityResidentMapper communityResidentMapper;

    @Autowired
    private CommunityRoomResidentServiceImpl communityRoomResidentService;
    /**
     * 查询住户管理
     * 
     * @param id 住户管理主键
     * @return 住户管理
     */
    @Override
    public CommunityResident selectCommunityResidentById(Long id)
    {
        return communityResidentMapper.selectCommunityResidentById(id);
    }

    /**
     * 查询住户管理列表
     * 
     * @param communityResidentDto 住户管理
     * @return 住户管理
     */
    @Override
    public List<CommunityResident> selectCommunityResidentList(CommunityResidentDto communityResidentDto)
    {
        return communityResidentMapper.selectCommunityResidentList(communityResidentDto);
    }

    /**
     * 新增住户管理
     * 
     * @param communityResident 住户管理
     * @return 结果
     */
    @Override
    public int insertCommunityResident(CommunityResident communityResident) throws Exception {

        if (residentPhoneExists(communityResident.getPhone())) {
            throw new Exception("电话号码已存在");
        }
        return communityResidentMapper.insertCommunityResident(communityResident);
    }

    private boolean residentPhoneExists(String residentPhone) {
        return communityResidentMapper.countByPhone(residentPhone) > 0;
    }

    /**
     * 修改住户管理
     *
     * @param communityResident 住户管理
     * @return 结果
     */
    @Override
    public int updateCommunityResident(CommunityResident communityResident) throws Exception {

        CommunityResident existingResident = communityResidentMapper.selectCommunityResidentById(communityResident.getId());

        if (existingResident == null) {
            throw new Exception("待更新的住户不存在");
        }

        // 只允许更新电话号码以外的属性
        CommunityResident updatedResident = new CommunityResident();
        updatedResident.setId(communityResident.getId());
        updatedResident.setName(communityResident.getName());
        updatedResident.setSex(communityResident.getSex());
        updatedResident.setRemark(communityResident.getRemark());
        updatedResident.setUpdateTime(DateUtils.getNowDate());

        // 更新前检查电话号码是否已存在（除当前记录外）
        CommunityResident residentWithSamePhone = communityResidentMapper.getResidentByPhone(communityResident.getPhone());
        if (residentWithSamePhone != null && !residentWithSamePhone.getId().equals(communityResident.getId())) {
            throw new Exception("社区中存在另一个居民，电话号码不能更新为已使用的号码");
        } else {
            // 电话号码未被其他住户使用或电话号码未变，可以更新
            updatedResident.setPhone(communityResident.getPhone());
        }

        return communityResidentMapper.updateCommunityResident(updatedResident);
    }
    /**
     * 批量删除住户管理
     * 
     * @param ids 需要删除的住户管理主键
     * @return 结果
     */
    @Override
    public int deleteCommunityResidentByIds(Long[] ids)
    {
        for(int i = 0; i <= ids.length; i++){
            i = (int)(long)ids[i];
            communityRoomResidentService.deleteCommunityRoomResidentById(i);
        }
        return communityResidentMapper.deleteCommunityResidentByIds(ids);
    }

    /**
     * 删除住户管理信息
     * 
     * @param id 住户管理主键
     * @return 结果
     */
    @Override
    public int deleteCommunityResidentById(Long id)
    {
        return communityResidentMapper.deleteCommunityResidentById(id);
    }

    @Override
    public CommunityResident getByName(String name) {
        return communityResidentMapper.getResidentByName(name);
    }

    @Override
    public CommunityResident getByPhone(String phone) {
        return communityResidentMapper.getResidentByPhone(phone);
    }

    @Override
    public int importCommunityResident(MultipartFile file) throws Exception {
        int rowsAffected = 0;

        // 创建一个 Workbook 对象来读取 Excel 文件
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            // 遍历工作表中的所有行
            for (Row row : sheet) {
                // 跳过表头行
                if (row.getRowNum() == 0) {
                    continue;
                }
                //从表格中提取数据
                String residentName = getStringCellValue(row, 0);
                Long residentPhone = null;
                Cell phoneCell = row.getCell(1);
                residentPhone = (long) phoneCell.getNumericCellValue();

//                String residentSex = getStringCellValue(row, 2);

                Long residentSex = null;
                Cell SexCell = row.getCell(2);
                residentSex = (long) SexCell.getNumericCellValue();
                // 创建 CommunityFacilities 对象并设置属性
                CommunityResident resident = new CommunityResident();
                resident.setName(residentName);
                resident.setPhone(String.valueOf(residentPhone));
                resident.setSex(residentSex);


                // 调用 insertCommunityFacilities 方法插入单个设施
                try {
                    rowsAffected += insertCommunityResident(resident);
                } catch (Exception e) {
                    // 记录或处理插入失败的异常（例如记录日志、忽略错误行等）
                }
            }
        }

        return rowsAffected;
    }
                // 从单元格中提取数据

    private String getStringCellValue(Row row, int cellIndex) {
        Cell cell = row.getCell(cellIndex);
        return cell != null ? cell.getStringCellValue().trim() : "";
    }

}
